package test

import cn.hutool.core.util.RandomUtil
import com.gitee.ixtf.guice.Jguice
import com.gitee.ixtf.vertx.guice.VertxGuice
import com.gitee.ixtf.vertx.rabbitmq.guice.RabbitMQGuice
import com.gitee.ixtf.vertx.rabbitmq.queueMessage
import com.gitee.ixtf.vertx.rabbitmq.send
import com.gitee.ixtf.vertx.rabbitmq.topicMessage
import com.gitee.ixtf.vertx.rabbitmq.verticle.RabbitMQConsumerVerticle
import io.vertx.core.DeploymentOptions
import io.vertx.core.Launcher
import io.vertx.core.Vertx
import io.vertx.core.VertxOptions
import io.vertx.ext.web.common.WebEnvironment
import io.vertx.kotlin.coroutines.coAwait
import io.vertx.rabbitmq.RabbitMQMessage
import io.vertx.rabbitmq.RabbitMQOptions
import java.time.Duration
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

fun main(args: Array<String>) {
  System.setProperty(WebEnvironment.SYSTEM_PROPERTY_NAME, "dev")
  System.setProperty("ixtf.api.service", "test")
  System.setProperty("ixtf.api.port", "30000")
  ServiceLauncher().dispatch(args)
}

private class TestMqVerticle : RabbitMQConsumerVerticle() {
  override val queue = "test"
  override val error = "${queue}:Error"

  override suspend fun handle(delivery: RabbitMQMessage) {
    println("${delivery.body()}")
    delay(10.seconds)
  }
}

private class ServiceLauncher : Launcher() {
  override fun getMainVerticle(): String = TestMqVerticle::class.java.name

  override fun beforeStartingVertx(options: VertxOptions) {
    with(options) { maxWorkerExecuteTime = Duration.ofHours(1).toNanos() }
  }

  override fun afterStartingVertx(vertx: Vertx) {
    super.afterStartingVertx(vertx)
    Runtime.getRuntime().addShutdownHook(Thread { runBlocking { vertx.close().coAwait() } })
    Jguice.init(TestMqModule(vertx))

    runBlocking { test() }
  }

  private suspend fun test() {
    topicMessage("test.123", RandomUtil.randomString(6)).send()
    queueMessage("test", RandomUtil.randomString(6)).send()
  }

  override fun handleDeployFailed(
      vertx: Vertx,
      mainVerticle: String,
      deploymentOptions: DeploymentOptions?,
      cause: Throwable?
  ) {
    cause?.printStackTrace()
    exitProcess(1)
  }
}

private class TestMqModule(private val vertx: Vertx) : RabbitMQGuice() {
  override fun configure() {
    super.configure()
    install(VertxGuice(vertx))
  }

  override fun prepare(options: RabbitMQOptions) {
    options.host = "172.10.100.112"
    options.user = "admin"
    options.password = "medipath888"
  }
}
